package com.atgugu.flink.chapter11;

import com.atgugu.flink.bean.WaterSensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

/**
 * @Author lzc
 * @Date 2022/4/11 9:12
 */
public class Flink07_SQL_BaseUse {
    public static void main(String[] args) {
        // 流->动态表->连续查询->动态表->流
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
    
        SingleOutputStreamOperator<WaterSensor> stream = env
            .fromElements(
                new WaterSensor("sensor_1", 1000L, 1),
                new WaterSensor("sensor_2", 2000L, 2),
                new WaterSensor("sensor_1", 3000L, 3),
                new WaterSensor("sensor_1", 4000L, 4),
                new WaterSensor("sensor_2", 5000L, 5),
                new WaterSensor("sensor_1", 6000L, 6)
            );
    
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        
        Table table = tEnv.fromDataStream(stream);
        
        // 在table上使用sql语句来执行查询
        
        // 1. 在未注册的表上执行查询
        //tEnv.executeSql(" ddl和增删改  sql语句"); // 用来执行 ddl和增删改
       // tEnv.sqlQuery("查询sql语句"); // 用来执行查询语句
       // tEnv.sqlQuery("select * from " + table + " where id='sensor_1'").execute().print();
        
        // 2. 在已注册的表上执行查询
        tEnv.createTemporaryView("sensor", table);  // 给table对象注册一个临时表
//        tEnv.sqlQuery("select * from sensor where id='sensor_1'").execute().print();
        tEnv.sqlQuery("select id, sum(vc) vc_sum from sensor group by id").execute().print();
        
        
    }
}
